﻿$(function () {
    $(ApartmentGallery).each(function () {
        SetApartmentGallery(this);
    });
});

function SetApartmentGallery(gallery) {
    var $panel = $(gallery.PanelSelector);
    var $img = $('<img class="crn-gallery" />').load(function () {
        $panel.append($(this));
        $panel.width($panel.width());
        $panel.height($panel.height());
    }).attr('src', gallery.Images[0].DisplayUrl);

    $panel.find('.dyngal-next').click(function () {
        GotoNextApartGallery(gallery);
    });
    $panel.find('.dyngal-prev').click(function () {
        GotoPreviousApartGallery(gallery);
    });
}

function GotoNextApartGallery(gallery) {
    GotoApartGallery(gallery, 1);
}

function GotoPreviousApartGallery(gallery) {
    GotoApartGallery(gallery, -1);
}

function GotoApartGallery(gallery, changeIndexBy) {
    var $panel = $(gallery.PanelSelector);
    var $crnImg = $panel.find('img.crn-gallery');
    var $prev = $panel.find('img.dyngal-prev');
    var $next = $panel.find('img.dyngal-next');
    var $counter = $panel.find('.dynamic-gallery-counter');
    var $desc = $panel.find('.dynamic-gallery-description');

    var idx = 0;
    if ($panel.data('image-idx'))
        idx = parseInt($panel.data('image-idx'));

    idx = idx + changeIndexBy;

    if (idx == 0)
        $prev.hide();
    else
        $prev.show();

    if ((idx + 1) == gallery.Images.length)
        $next.hide();
    else
        $next.show();

    $counter.text((idx + 1));
    $desc.text(gallery.Images[idx].Description);

    $panel.data('image-load-src', gallery.Images[idx].DisplayUrl);

    $crnImg.remove();
    var $img = $('<img class="crn-gallery" />').load(function () {
        if ($panel.data('image-idx') == idx) {
            $img.hide();
            $panel.append($img);
            $img.fadeIn();
        }
    }).attr('src', gallery.Images[idx].DisplayUrl);
    $panel.data('image-idx', idx);
}